var ToolMaintainTableInit = function () {
    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#toolMaintainTable').bootstrapTable({
            url: ctx + '/tool/maintain/getToolMaintainList/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop: false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect: false,                    //禁止多选
            checkboxHeader: true,                 //列头取消多选
            columns: [
                {
                    radio: true,
                    align: 'center',
                    valign: 'middle'
                },
                {
                    title: '序号',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        var options = $('#toolMaintainTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'toolCode',
                    title: '工装编码',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolName',
                    title: '工装名称',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolModel',
                    title: '工装型号',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolTypeValue',
                    title: '工装类别',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'opName',
                    title: '使用工序',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'maintainCycle',
                    title: '保养周期',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'lastMaintainDate',
                    title: '上次保养日期',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'nextMaintainDate',
                    title: '下次保养日期',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value) {
                        if(new Date().format("yyyy-MM-dd") < value) {
                            return value
                        } else {
                            return "<span style='color: red;'>"+value+"</span>"
                        }
                    }

                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible: false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            toolCode: $("#toolCode").find("option:selected").text(),
            toolName: $("#toolName").val(),
            toolModel: $("#toolModel").val(),
            toolType: $("#toolType").val(),
            nextMaintainDateStart: $("#nextMaintainDateStart").val(),
            nextMaintainDateEnd: $("#nextMaintainDateEnd").val()
        }
    };
    return oTableInit;
};

jQuery(document).ready(function () {
    //1.初始化Table
    var oTable = new ToolMaintainTableInit();
    oTable.Init();
    //初始化页面
    toolMaintainInit.init();
});


var toolMaintainInit = function () {
    return {
        init: function () {
            SystemCommon.getSysDict('TOOL_TYPE','tool-type');
            toolMaintainInit._getToolInfo();
            toolMaintainInit._modalHidden();
            toolMaintainInit._initToolCodeQuerySelect2();
            toolMaintainInit._initWorkNoSelect2();
            toolMaintainInit._initWorkNoSelectChange();
            toolMaintainInit._initConfirmUserSelect2();
            toolMaintainInit._initDateControl();
            toolMaintainInit._validatorForm();
            toolMaintainInit._maintain();
            toolMaintainInit._query();
            toolMaintainInit._keyQuery();
            toolMaintainInit._refresh();
            toolMaintainInit._reset();
            toolMaintainInit._save();
        },
        //条件查询
        _query: function () {
            $("#queryToolMaintain").on("click", function () {
                $('#toolMaintainTable').bootstrapTable('refreshOptions', {
                    pageNumber: 1
                });
            });
        },
        //按键查询
        _keyQuery: function () {
            $(".tool-maintain-search").keypress(function (e) {
                if (e.which === 13) {
                    $("#queryToolMaintain").trigger("click");
                }
            });
        },
        //重置查询
        _reset: function () {
            $(".reset").on("click", function () {
                $(".clearfix input").val("");
                $("#toolCodeQuerySelect2").val(null).trigger("change");
                $("#toolType").val("");
            });

        },
        _refresh: function () {
            //刷新
            $("#refreshTable").on("click", function () {
                $('#toolMaintainTable').bootstrapTable('refresh');
            });
        },
        _initDateControl: function () {
            $('.form-datetime').datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss',
                language: 'zh-CN',
                autoclose: true,
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
            $('.form-datetime-day').datetimepicker({
                format: 'yyyy-mm-dd',
                minView: 2,
                autoclose: true,
                language: 'zh-CN',
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        //新增
        _maintain: function () {
            $("#maintain").on('click', function (e) {
                e.preventDefault();
                $('#myModal .title').html("保养");
                var toolCode = $.map($('#toolMaintainTable').bootstrapTable('getSelections'), function (row) {
                    return row.toolCode;
                });
                if (toolCode.length !== 1) {
                    DialogUtil.warning("请选择一行记录");
                    return false;
                }
                //解决select2无法输入问题
                $.fn.modal.Constructor.prototype.enforceFocus = function () {
                    $("#myModal select").focus();
                };
                $.ajax({
                    url: ctx + "/tool/maintain/getToolMaintainInfo/get.mvc",
                    type: "post",
                    dataType: "json",
                    data: {
                        toolCode: toolCode.toString()
                    },
                    success: function (response) {
                        //debugger
                        if (response.result === true) {
                            if(response.data) {
                                var _data = response.data;
                                $("#toolMaintainForm").find("input[name=toolCode]").val(_data.toolCode);
                                $("#toolMaintainForm").find("input[name=toolName]").val(_data.toolName);
                                var _itemList = _data.maintainItemList;
                                var tbody = $("#itemTableTbody");
                                tbody.empty();
                                for (var i = 0; i < _itemList.length; i++) {
                                    var tr = $("<tr>" +
                                        "<td>"+(i+1)+"</td>" +
                                        "<td class='maintain-item-code' data-id='"+_itemList[i].maintainItemId+"'>"+_itemList[i].maintainCode+"</td>" +
                                        "<td>"+_itemList[i].maintainName+"</td>" +
                                        "<td>"+_itemList[i].maintainMethod+"</td>" +
                                        "<td class='maintain-item-remark' contenteditable=\"true\"></td>" +
                                        "<td class='maintain-item-result' contenteditable=\"true\"></td>" +
                                        "</tr>");
                                    tbody.append(tr);

                                }
                                $('#myModal').modal();
                            }
                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function () {
                        DialogUtil.error("系统繁忙！");
                    }
                });

            });
        },
        _initWorkNoSelect2 : function () {
            $('#maintainUserWorkNo').select2({
                ajax: {
                    url: ctx +'/tool/maintain/getUserPageList/get.mvc',
                    dataType: 'json',
                    aynsc :false,
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            num: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test =[];
                        if(response.result === true&&response.data){
                            var _data = response.data;
                            for ( var int = 0; int < _data.length; int++) {
                                var obj={};
                                obj.id=_data[int].username;
                                obj.text=_data[int].workNo;
                                test.push(obj);
                            }
                            return {
                                results: test
                            };
                        }
                        return null;
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
        _initWorkNoSelectChange:function () {
            $("#maintainUserWorkNo").on("change",function () {
                var username = $("#maintainUserWorkNo").val();
                $.ajax({
                    url: ctx + "/tool/maintain/getUserInfoByUserName/get.mvc",
                    type: "post",
                    dataType: "json",
                    data: {
                        username: username
                    },
                    success: function (response) {
                        //debugger
                        if (response.result === true) {
                            if(response.data) {
                                $("#toolMaintainForm").find("input[name=maintainUsername]").val(response.data.truename);
                            }
                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function () {
                        DialogUtil.error("系统繁忙！");
                    }
                });
            })
        },
        _initConfirmUserSelect2 : function () {
            $('#confirmUser').select2({
                ajax: {
                    url: ctx +'/system/user/getSysUserList/get.mvc',
                    dataType: 'json',
                    aynsc :false,
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            num: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test =[];
                        if(response.result === true&&response.data){
                            var _data = response.data;
                            for ( var int = 0; int < _data.length; int++) {
                                var obj={};
                                obj.id=_data[int].username;
                                obj.text=_data[int].truename;
                                test.push(obj);
                            }
                            return {
                                results: test
                            };
                        }
                        return null;
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
        //表单校验
        _validatorForm: function () {
            $("#toolMaintainForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {
                    /*验证*/
                    toolCode: {
                        message: '工装编码无效',
                        validators: {
                            notEmpty: {
                                message: '工装编码不能为空'
                            }
                        }
                    },
                    maintainUser: {
                        message: '保养人工号无效',
                        validators: {
                            notEmpty: {
                                message: '保养人工号不能为空'
                            }
                        }
                    },
                    maintainDate: {
                        message: '保养日期无效',
                        validators: {
                            notEmpty: {
                                message: '保养日期不能为空'
                            }
                        }
                    },
                    maintainUsername: {
                        message: '保养人不能为空',
                        validators: {
                            notEmpty: {
                                message: '保养人不能为空'
                            }
                        }
                    },
                    remark: {
                        message: '备注不能超过40字符',
                        validators: {
                            stringLength: {
                                max: 40,
                                message: '备注不能超过40字符'
                            }
                        }
                    }
                }
            });
        },
        _save: function () {
            $("#myModal .yes").on("click", function (e) {
                $("#myModal .yes").attr("disabled", true);
                e.preventDefault();
                /*$("#toolMaintainForm").data("bootstrapValidator").validate();
                var flag = $("#toolReplacePlanForm").data("bootstrapValidator").isValid();
                if (!flag) {
                    $("#myModal .yes").attr("disabled", false);
                    //未通过验证
                    return false;
                }*/
                var entity = {};
                entity['toolCode'] = $("#toolMaintainForm").find("input[name=toolCode]").val();
                entity['maintainUser'] = $("#toolMaintainForm").find("select[name=maintainUser]").val();
                entity['maintainDate'] = $("#toolMaintainForm").find("input[name=maintainDate]").val();
                entity['confirmUser'] = $("#toolMaintainForm").find("select[name=confirmUser]").val();
                entity['confirmDate'] = $("#toolMaintainForm").find("input[name=confirmDate]").val();
                entity['remark'] = $("#toolMaintainForm").find("textarea[name=remark]").val();
                var maintainItemList = [];
                //debugger
                var itemList = $("#itemTableTbody tr");
                for (var i = 0; i < itemList.length; i++) {
                    //var maintainCode = $(itemList[i]).find("td.maintain-item-code").text();
                    var remark = $(itemList[i]).find("td.maintain-item-remark").text();
                    var maintainResult = $(itemList[i]).find("td.maintain-item-result").text();
                    var maintainItemId = $(itemList[i]).find("td.maintain-item-code").data("id");
                    maintainItemList.push({
                        /*
                         *   2018-07-30 modify by zhanghailin
                         *   修改关联字段为id
                         */
                        "maintainItemId":maintainItemId,
                        //"maintainCode":maintainCode,
                        "remark":remark,
                        "maintainResult":maintainResult
                    })
                }
                entity['maintainItemList'] = maintainItemList;
                console.log(entity);
                $.ajax({
                    url: ctx + '/tool/maintain/toolMaintain/save.mvc',
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(entity),
                    success: function (response) {
                        if (response.result === true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#myModal').modal('hide');
                            $('#toolMaintainTable').bootstrapTable('refresh');
                        } else {
                            DialogUtil.error(response.message);
                        }
                        $("#myModal .yes").attr("disabled", false);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $("#myModal .yes").attr("disabled", false);
                        console.log(errorThrown);
                        DialogUtil.error("系统错误");
                    }
                });

            });
        },
        _initToolCodeQuerySelect2: function () {
            $('#toolCodeQuerySelect2').select2({
                ajax: {
                    url: ctx + '/tool/toolInfo/listToolInfoByFilter/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            toolCode: params.term,
                            num: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response,params) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        params.page = params.page || 1;
                        var test =[];
                        if(response.rows) {
                            var _data = response.rows;
                            for ( var int = 0; int < _data.length; int++) {
                                var obj= {};
                                obj.id=_data[int].pkId;
                                obj.text=_data[int].toolCode;
                                test.push(obj);
                            }
                        }
                        return {
                            results: test,
                            pagination :{
                                more:(params.page * 10) < response.total
                            }
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: false

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
        //工装编码下拉框change查询工装信息
        _getToolInfo: function () {
            $("#toolCodeQuerySelect2").on("change", function (e) {
                e.preventDefault();
                var toolId = $("#toolCodeQuerySelect2").val();
                console.log(toolId);
                $.ajax({
                    url: ctx + '/tool/toolInfo/getToolInfoById/get.mvc',
                    type: "post",
                    dataType: 'json',
                    data: {
                        pkId: toolId
                    },
                    success: function (response) {
                        console.log(response);
                        if (response.result === true) {
                            var _data = response.data;
                            if (_data) {
                                $("#toolName").val(_data.toolName);
                                $("#toolModel").val(_data.toolModel);
                                $("#toolType").val(_data.toolType);
                            }

                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        DialogUtil.error(errorThrown);
                    }
                });
            })
        },
        _modalHidden: function () {
            //模态框消失清空信息
            $("#myModal").on("hide.bs.modal", function () {
                $('#myModal input').each(function () {
                    if ($(this).val() !== "") {
                        $(this).val("");
                    }
                });
                $("#remark").val('');
                $("#confirmUser").val(null).trigger("change");
                $("#maintainUserWorkNo").val(null).trigger("change");
                $("#itemTableTbody").empty();
                $('#toolMaintainForm').bootstrapValidator('resetForm', false);
            });
        }
    }
}();